package cn.chenfeifx.checker.model;

import cn.chenfeifx.checker.CheckerApp;
import cn.chenfeifx.checker.eneity.ExportDataModel;
import cn.chenfeifx.checker.eneity.MessageEntity;
import cn.chenfeifx.checker.eneity.Report;
import cn.chenfeifx.checker.enums.CheckerEnum;
import cn.chenfeifx.checker.thread.CheckRunable;
import cn.chenfeifx.checker.thread.SplitRunable;
import cn.chenfeifx.core.common.LoadingUtils;
import cn.chenfeifx.core.common.SimpleButton;
import cn.chenfeifx.core.controls.*;
import cn.chenfeifx.core.controls.model.Column;
import cn.chenfeifx.core.enums.Level;
import com.alibaba.excel.EasyExcel;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.application.Platform;
import javafx.scene.layout.VBox;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;


public class CheckNav  extends StackPane {

    private CFTableView cfTableView = CheckerApp.getInstance().getCfTableView();
    private CFFileChooser cfFileChooser = new CFFileChooser();
    Button button2 = SimpleButton.get("加载著录表", Level.SUCCESS);
    Button button3 = SimpleButton.get("开始质检", Level.SUCCESS);
    Button button4 = SimpleButton.get("导出报告", Level.SUCCESS);
    Button button5 = SimpleButton.get("开始分件", Level.SUCCESS);
    HBox hBox = new HBox(cfFileChooser,button2,button3,button4);
    HBox hBox2 = new HBox(cfTableView);
    VBox vBox = new VBox(hBox,hBox2);

    String maxreference = "";

    String minreference = "";
    public CheckNav() {
        hBox.setMaxSize(USE_PREF_SIZE, USE_PREF_SIZE);
//        hBox.setAlignment(Pos.TOP_LEFT);
        hBox.setSpacing(10);
        getChildren().addAll(vBox);
        AtomicBoolean loading = new AtomicBoolean(false);
        setPadding(new Insets(20));
        ExecutorService executor = Executors.newFixedThreadPool(8); // 创建固定大小的线程池
        BlockingQueue<Report> queue = new LinkedBlockingQueue<>();
        Set<Report> reports = new HashSet<>();
        List<Future<?>> futureList = new ArrayList<>();



        button3.setDisable(true);
        button4.setDisable(false);
        button5.setDisable(true);
        // 创建列
        List<Column> columns = Arrays.asList(
                new Column("全宗号","completeNumber",150d),
                new Column("类目号","categoryNumber",100d),
                new Column("案卷号","caseFileNumber",100d),
                new Column("档号","reference",150d),
                new Column("案卷题名","titleName",100d),
                new Column("件数","caseNumber",100d),
                new Column("页数","pageNumber",50d),
                new Column("保管期限","term",150d),
                new Column("年度","year",100d),
                new Column("密级","security",100d),
                new Column("开放状态","security",100d),
                new Column("备注","remark",100d)

        );
        TableColumn<Report,String> photoColumn = new TableColumn<>("状态");
        photoColumn.setCellFactory(column ->new TableCell<Report, String>() {
            private final ImageView imageView = new ImageView();
            {
                imageView.setFitWidth(20);
                imageView.setFitHeight(20);
            }

            @Override
            protected void updateItem(String status, boolean empty) {
                super.updateItem(status, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    if( status!=null){
                        Image image = new Image(status);
//                        Image image = new Image("/img/loading.gif");
                        imageView.setImage(image);
                        setGraphic(imageView);
                    }
                }
            }
        });
        photoColumn.setCellValueFactory(cellData ->cellData.getValue().getStatusPath());
        cfTableView.createColumns(columns);
        cfTableView.getColumns().add(photoColumn);


        button2.setOnMouseClicked(event ->
            LoadingUtils.nodeLoad(this, () -> {
                //模拟数据
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        // 在这个里边可以执行业务逻辑
                        try {
                            if(cfFileChooser.getFile()==null){
                                CFMessage.show("请选择文件", Level.DANGER);
                            }
                            File file = cfFileChooser.getFile();
                            List<Report> reports = EasyExcel.read(new FileInputStream(file)).head(Report.class)
                                    .sheet()
                                    .doReadSync();
                            int index = 1;
                            if(reports!=null){
                                for (Report report : reports){
                                    report.setIndex(index++);
                                    report.setStatusPath("/img/loading.gif");
                                }
                                // 设置数据
                                cfTableView.setItems(reports);
                                button2.setDisable(true);
                                button3.setDisable(false);
                                button5.setDisable(false);
                                maxreference = reports.get(reports.size()-1).getReference();
                                minreference = reports.get(0).getReference();
                            }


                        } catch (FileNotFoundException e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
                return true;
        }));
        button3.setOnMouseClicked(event ->
                LoadingUtils.nodeLoad(this,() -> {
//                    loading.set(true);
                    button3.setDisable(true);
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            // 在这个里边可以执行业务逻辑
                            try {
                                File file = cfFileChooser.getFile();
                                String parentPath = file.getParent();
                                List<Report> items = cfTableView.getItems();
                                // 校验案卷
                                Integer index = 1;
                                for (Report report : items){
                                        Future<?> submit = executor.submit(new CheckRunable(
                                                index++,
                                                report,
                                                parentPath));
                                        futureList.add(submit);
                                }
                                //queue.addAll(items);
                                /*for (int i = 0; i < 8; i++) {
                                    Future<?> submit = executor.submit(new CheckRunable(index++,queue, parentPath));
                                    futureList.add(submit);
                                }*/

                                executor.shutdown(); // 关闭线程池

                            } catch (Exception e) {
                                CFMessage.show("质检失败", Level.DANGER);
                                throw new RuntimeException(e);

                            }
                        }
                    });
                     new Runnable(){
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                            int completedTasks = 0;
                            while (true) {
                                int currentCompletedTasks = 0;
                                for (Future<?> future : futureList) {
                                    if (future.isDone()) {
                                        currentCompletedTasks++;
                                    }
                                }
                                if (currentCompletedTasks > completedTasks) {
                                    completedTasks = currentCompletedTasks;
                                    System.out.println("Completed tasks: " + completedTasks + ", still waiting...");
                                }
                                if (completedTasks == futureList.size()) {
                                    System.out.println("所有线程任务已完成");
                                    button4.setDisable(false);
                                    CFMessage.show("质检完成", Level.SUCCESS);
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt();
                                }
                            }

                        }
                    };
                    return true;
                }));
        button4.setOnMouseClicked(event ->
                LoadingUtils.nodeLoad(this,() -> {
//                    button4.setDisable(true);
                    Platform.runLater(
                        new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if(cfFileChooser.getFile()==null){
                                        CFMessage.show("请选择文件", Level.DANGER);
                                    }
                                    String parent = cfFileChooser.getFile().getParent();
                                    List<MessageEntity> messageList = CheckerApp.getInstance().getMessageList(CheckerEnum.FILES.getCode());
                                    List<ExportDataModel> reports = CheckerApp.getInstance().getReports(CheckerEnum.FILES.getCode());

                                    ExportFile.exportExcel(
                                            parent+"/永和县档案馆文书档案数据质量检测记录表.xlsx",
                                            reports,
                                            "",
                                            "",
                                            ExportFile.addFile(parent),
                                            minreference+"-"+maxreference);

//                                    EasyExcel.write( new FileOutputStream(new File(parent+"/质检报告.xlsx")), Report.class)
//                                            .autoCloseStream(Boolean.FALSE)
//                                            .sheet("质检报告")
//                                            .doWrite(reports);
                                    EasyExcel.write( new FileOutputStream(new File(parent+"/案卷错误详情.xlsx")), MessageEntity.class)
                                            .autoCloseStream(Boolean.FALSE)
                                            .sheet("错误详情")
                                            .doWrite(sortList(messageList));
                                    CFMessage.show("报告导出成功，请在目录文件夹下查看！", Level.SUCCESS);

                                } catch (FileNotFoundException e) {
                                    throw new RuntimeException(e);
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    );
                    return true;
                }));

//        Platform.runLater(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    while (true){
//                        // 检查每个任务是否完成
//                        boolean allDone = true;
//                        if(futureList.size()>0){
//                            for (Future<?> future : futureList) {
//                                try {
//                                    allDone &= future.isDone();
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                            if (allDone) {
//                                System.out.println("所有线程任务已完成");
//                                button4.setDisable(false);
//                                CFMessage.show("质检完成", Level.DANGER);
//
//                                break;
//                            } else {
//                                System.out.println("还有任务未完成");
//                            }
//                        }
//
//                    }
//
//                }catch (Exception e){
//                    CFMessage.show("质检失败", Level.DANGER);
//                }
//            }
//        });

        button5.setOnMouseClicked(event ->
                LoadingUtils.nodeLoad(this,() -> {
//                    loading.set(true);
                    button5.setDisable(true);
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            // 在这个里边可以执行业务逻辑
                            try {
                                File file = cfFileChooser.getFile();
                                String parentPath = file.getParent();
                                List<Report> items = cfTableView.getItems();
                                // 校验案卷
                                Integer index = 1;
                                for (Report report : items){
                                    Future<?> submit = executor.submit(new SplitRunable(index++,
                                            report.getReference(),
                                            report.getTitleName(),
                                            report.getYear(),
                                            report.getPageNumber(),
                                            report.getTerm(),
                                            report.getRemark(),
                                            report.getCaseNumber(),
                                            parentPath));
                                    futureList.add(submit);
                                }
                                executor.shutdown(); // 关闭线程池


                            } catch (Exception e) {
                                CFMessage.show("分件失败", Level.DANGER);
                                throw new RuntimeException(e);

                            }
                        }
                    });
                    new Runnable(){
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(3000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                            int completedTasks = 0;
                            while (true) {
                                int currentCompletedTasks = 0;
                                for (Future<?> future : futureList) {
                                    if (future.isDone()) {
                                        currentCompletedTasks++;
                                    }
                                }
                                if (currentCompletedTasks > completedTasks) {
                                    completedTasks = currentCompletedTasks;
                                    System.out.println("Completed tasks: " + completedTasks + ", still waiting...");
                                }
                                if (completedTasks == futureList.size()) {
                                    System.out.println("所有线程任务已完成");
                                    button4.setDisable(false);
                                    CFMessage.show("质检完成", Level.SUCCESS);
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt();
                                }
                            }

                        }
                    };

                    return true;
                }));
    }

    public static List<MessageEntity> sortList(List<MessageEntity> list){

        Comparator<MessageEntity> comparatorByAgeDesc = (map1, map2) -> {
            String value1 = map1.getReference();
            String value2 = map2.getReference();
            return - value2.compareTo(value1);
        };
        Collections.sort(list, comparatorByAgeDesc);
        return list;
    }

}